package com.junxonline.plat.service.house.impl;

import com.junxonline.common.util.CommonUtils;
import com.junxonline.common.util.FileUtils;
import com.junxonline.plat.dao.model.House;
import com.junxonline.plat.dao.model.HouseFloorPlan;
import com.junxonline.plat.dao.model.Household;
import com.junxonline.plat.dao.model.Position;
import com.junxonline.plat.dao.repository.FloorPlanRepository;
import com.junxonline.plat.dao.repository.HouseRepository;
import com.junxonline.plat.dao.repository.HouseholdRepository;
import com.junxonline.plat.dao.vo.*;
import com.junxonline.plat.service.house.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class HouseServiceImpl implements HouseService {

    @Autowired
    private HouseRepository houseRepository;

    @Autowired
    private HouseholdRepository householdRepository;

    @Autowired
    private FloorPlanRepository floorPlanRepository;

    /**
     * 获取房产数据
     *
     * @param vo
     * @return
     */
    @Override
    public HouseVO getHouse(QueryHouseVO vo) {

        House house = houseRepository.findByHouseId(vo.getHouseId());

        HouseVO houseVO = new HouseVO();

        houseVO.setHouseId(house.getHouseId());
        houseVO.setHouseNo(house.getHouseNo());

        houseVO.setBuildingNo(house.getBuildingNo());
        houseVO.setUnitNo(house.getUnitNo());
        houseVO.setRoomNo(house.getRoomNo());

        houseVO.setBedRoomCount(house.getBedRoomCount());
        houseVO.setLivingRoomCount(house.getLivingRoomCount());
        houseVO.setKitchenCount(house.getKitchenCount());
        houseVO.setToiletCount(house.getToiletCount());

        houseVO.setUpdateAfterNo(house.getUpdateAfterNo());
        houseVO.setUpdateTime(house.getUpdateTime());
        houseVO.setUpdateUserId(house.getUpdateUserId());
        houseVO.setHouseholdName(house.getUpdateUserName());

        Household household = house.getHousehold();

        if (CommonUtils.isNotEmpty(household)) {
            houseVO.setHouseholdId(household.getHouseholdId());
            houseVO.setHouseholdName(household.getHouseholdName() + "(" + household.getHouseholdNo() + ")");
        }

        HouseFloorPlan floorPlan = house.getHouseFloorPlan();

        if (CommonUtils.isNotEmpty(floorPlan)) {
            houseVO.setFloorPlanId(floorPlan.getHouseFloorPlanId());
            houseVO.setFloorPlanName(floorPlan.getHouseFloorPlanName());
        }

        return houseVO;
    }

    /**
     * 筛选查询房产
     *
     * @param pageVO
     * @param vo
     * @return
     */
    @Override
    public PageVO queryHouse(PageVO pageVO, QueryHouseVO vo) {
        PageRequest pageRequest = PageRequest.of(pageVO.getPage() - 1, pageVO.getLimit(), new Sort(Sort.Direction.ASC, "houseId"));

        Page<House> page = houseRepository.findAll(new Specification<House>() {
            @Override
            public Predicate toPredicate(Root<House> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                List<Predicate> params = new ArrayList<>();
                String houseNo = vo.getHouseNo();
                String houseBuildingNo = vo.getHouseBuidingNo();
                String houseUnitNo = vo.getHouseUnitNo();
                String houseRoomNo = vo.getHouseRoomNo();

                if (CommonUtils.isNotEmpty(houseNo)) {
                    params.add(criteriaBuilder.like(root.get("houseNo"), "%" + houseNo + "%"));
                }

                if (CommonUtils.isNotEmpty(houseBuildingNo)) {
                    params.add(criteriaBuilder.like(root.get("buildingNo"), "%" + houseBuildingNo + "%"));
                }

                if (CommonUtils.isNotEmpty(houseUnitNo)) {
                    params.add(criteriaBuilder.like(root.get("unitNo"), "%" + houseUnitNo + "%"));
                }

                if (CommonUtils.isNotEmpty(houseRoomNo)) {
                    params.add(criteriaBuilder.like(root.get("roomNo"), "%" + houseRoomNo + "%"));
                }

                return criteriaBuilder.and(params.toArray(new Predicate[params.size()]));
            }
        }, pageRequest);

        List<HouseVO> houseVOs = new ArrayList<>();
        List<House> houses = page.getContent();

        for (House house : houses) {

            HouseVO houseVO = new HouseVO();

            houseVO.setHouseId(house.getHouseId());
            houseVO.setHouseNo(house.getHouseNo());

            houseVO.setBuildingNo(house.getBuildingNo());
            houseVO.setUnitNo(house.getUnitNo());
            houseVO.setRoomNo(house.getRoomNo());

            houseVO.setBedRoomCount(house.getBedRoomCount());
            houseVO.setLivingRoomCount(house.getLivingRoomCount());
            houseVO.setKitchenCount(house.getKitchenCount());
            houseVO.setToiletCount(house.getToiletCount());

            houseVO.setUpdateAfterNo(house.getUpdateAfterNo());
            houseVO.setUpdateTime(house.getUpdateTime());
            houseVO.setUpdateUserId(house.getUpdateUserId());
            houseVO.setUpdateUserName(house.getUpdateUserName());

            Household household = house.getHousehold();

            if (CommonUtils.isNotEmpty(household)) {
                houseVO.setHouseholdId(household.getHouseholdId());
                houseVO.setHouseholdName(household.getHouseholdName() + "(" + household.getHouseholdNo() + ")");
            }

            houseVOs.add(houseVO);

        }

        pageVO.setTotal(page.getTotalElements());
        pageVO.setData(houseVOs);

        return pageVO;
    }

    /**
     * 添加房产
     *
     * @param vo
     * @return
     */
    @Override
    public boolean addHouse(HouseVO vo) {

        House house = new House();

        StringBuilder houseNO = new StringBuilder();
        houseNO.append("RIDNO");


        House tempHouse = houseRepository.findByHouseIdLast();
        DecimalFormat decimalFormat = new DecimalFormat("000000");
        if (CommonUtils.isEmpty(tempHouse)) {
            houseNO.append("000001");
        } else {
            String currentNO = tempHouse.getHouseId().toString();
            String nextNO = decimalFormat.format(Integer.parseInt(currentNO) + 1);
            houseNO.append(nextNO);
        }

        house.setHouseNo(houseNO.toString());

        house.setBuildingNo(vo.getBuildingNo());
        house.setUnitNo(vo.getUnitNo());
        house.setRoomNo(vo.getRoomNo());

        house.setBedRoomCount(vo.getBedRoomCount());
        house.setLivingRoomCount(vo.getLivingRoomCount());
        house.setKitchenCount(vo.getKitchenCount());
        house.setToiletCount(vo.getToiletCount());

        // 设置时间
        if (CommonUtils.isNotEmpty(vo.getHouseholdId())) {

            Household household = householdRepository.findByHouseholdId(vo.getHouseholdId());

            if (CommonUtils.isNotEmpty(household)) {
                house.setHousehold(household);
                house.setUpdateTime(new Date());
            }

        }

        // 处理房产户型图
        if (CommonUtils.isNotEmpty(vo.getFloorPlanId())) {

            HouseFloorPlan floorPlan = floorPlanRepository.findByHouseFloorPlanId(vo.getFloorPlanId());

            if (CommonUtils.isNotEmpty(floorPlan)) {
                house.setHouseFloorPlan(floorPlan);
            }
        }

        houseRepository.save(house);

        return true;
    }

    /**
     * 修改房产
     *
     * @param vo
     * @return
     */
    @Override
    public boolean editHouse(HouseVO vo) {

        House house = houseRepository.findByHouseId(vo.getHouseId());

        StringBuilder houseUpdateNO = new StringBuilder();
        houseUpdateNO.append("RIDUPNO");

        house.setBuildingNo(vo.getBuildingNo());
        house.setUnitNo(vo.getUnitNo());
        house.setRoomNo(vo.getRoomNo());

        house.setBedRoomCount(vo.getBedRoomCount());
        house.setLivingRoomCount(vo.getLivingRoomCount());
        house.setKitchenCount(vo.getKitchenCount());
        house.setToiletCount(vo.getToiletCount());

        // 设置变更相关信息
        if (CommonUtils.isNotEmpty(vo.getHouseholdId())) {

            Household beforeHousehold = house.getHousehold();

            if (CommonUtils.isNotEmpty(beforeHousehold)) {
                house.setUpdateUserId(beforeHousehold.getHouseholdId());
                house.setUpdateUserName(beforeHousehold.getHouseholdName() + "(" + beforeHousehold.getHouseholdNo() + ")");
                house.setUpdateTime(new Date());
            }

            Household afterHousehold = householdRepository.findByHouseholdId(vo.getHouseholdId());
            house.setHousehold(afterHousehold);
        }

        House tempHouse = houseRepository.findByHouseIdLast();
        DecimalFormat decimalFormat = new DecimalFormat("000000");
        if (CommonUtils.isEmpty(tempHouse.getUpdateAfterNo())) {
            houseUpdateNO.append("000001");
            house.setUpdateTime(new Date());
        } else {
            String currentUpdateNO = tempHouse.getUpdateAfterNo().replace("RIDUPNO", "");
            String nextUpdateNO = decimalFormat.format(Integer.parseInt(currentUpdateNO) + 1);
            houseUpdateNO.append(nextUpdateNO);
            house.setUpdateTime(new Date());
        }

        house.setUpdateAfterNo(houseUpdateNO.toString());

        // 处理房产户型图
        if (CommonUtils.isNotEmpty(vo.getFloorPlanId())) {

            HouseFloorPlan floorPlan = floorPlanRepository.findByHouseFloorPlanId(vo.getFloorPlanId());

            if (CommonUtils.isNotEmpty(floorPlan)) {
                house.setHouseFloorPlan(floorPlan);
            }
        }

        houseRepository.save(house);

        return true;
    }

    /**
     * 删除房产
     *
     * @param houseIds
     * @return
     */
    @Override
    public boolean delHouse(Long[] houseIds) {

        List<House> houses = houseRepository.findByHouseIdIn(houseIds);

        for (House house : houses) {

            // 删除房产
            houseRepository.delete(house);

        }

        return true;
    }

    /**
     * 获取住户数据
     *
     * @param vo
     * @return
     */
    @Override
    public List<HouseholdVO> getHousehold(QueryHouseholdVO vo) {

        List<HouseholdVO> householdVOList = new ArrayList<>();
        List<Household> households = householdRepository.findByHouseholdNameLikeAndIsHousehold(vo.getHouseholdName(), 1);

        for (Household household : households) {

            HouseholdVO householdVO = new HouseholdVO();
            householdVO.setHouseholdId(household.getHouseholdId());
            householdVO.setHouseholdName(household.getHouseholdName());
            householdVO.setHouseholdNo(household.getHouseholdNo());
            householdVOList.add(householdVO);
        }

        return householdVOList;
    }

    /**
     * 获取户型数据
     *
     * @return
     */
    @Override
    public List<FloorPlanVO> getFloorPlan() {

        List<FloorPlanVO> floorPlanVOList = new ArrayList<>();
        List<HouseFloorPlan> floorPlans = floorPlanRepository.findAll();

        for (HouseFloorPlan floorPlan : floorPlans) {

            FloorPlanVO floorPlanVO = new FloorPlanVO();
            floorPlanVO.setHouseFloorPlanId(floorPlan.getHouseFloorPlanId());
            floorPlanVO.setHouseFloorPlanName(floorPlan.getHouseFloorPlanName());

            String imgBase64 = FileUtils.readFile(floorPlan.getHouseFloorPlanFilePath());

            floorPlanVO.setHouseFloorPlanFileBase64(imgBase64);
            floorPlanVOList.add(floorPlanVO);
        }

        return floorPlanVOList;
    }
}
